<?php

class Options extends CI_Controller {
	
	 public function __construct(){
		parent::__construct();		
		if(!is_admin_role('admin'))
			redirect(base_url('admin/login'));
		$this->load->model('option_m', 'option');
    }
	
	function index() {
		$data = array();
		$data['options']		= $this->option->get_options();
		$data['main_content'] = 'admin/options';
      $this->load->view('admin/includes/template', $data);
	}
	
	function form($id = false){
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->library('form_validation');
		
		//set the default values
		$data['id']				= '';
		$data['key']			= '';
		$data['value']	      = '';
		$data['desc']	      = '';
		$data['enabled']		= '';
		$data['page_title']	= 'Options Form';
		
		if($id){
			$option			= $this->option->get_option($id);
			if(!$option){
				//option does not exist
				$this->session->set_flashdata('error', 'Option không tìm thấy');
				redirect('admin/options');
			}
			//set values to db values
			$data['id']				= $option->id;
			$data['key']			= $option->key;
			$data['value']			= $option->value;
			$data['desc']			= $option->desc;
			$data['enabled']		= $option->enabled;
		}
		
		$this->form_validation->set_rules('key', 'lang:title', 'trim|required');
		$this->form_validation->set_rules('value', 'lang:subject', 'trim|required');
		$this->form_validation->set_rules('desc', 'lang:sequence', 'trim|required');
		
		// Validate the form
		if($this->form_validation->run() == false){
			$data['main_content'] = 'admin/option_form';
			$this->load->view('admin/includes/template', $data);
		}
		else{
			$this->load->helper('text');			
			//first check the slug field
			$slug = $this->input->post('slug');			
			//if it's empty assign the name field
			if(empty($slug) || $slug=='')
				$slug = $this->input->post('name');
			
			$slug	= str_replace("-","_",remove_accents($slug));
			$save = array();
			$save['id']			= $id;
			$save['key']		= $this->input->post('key');
			$save['value']		= $this->input->post('value'); 
			$save['desc']		= $this->input->post('desc');
			$save['enabled']	= $this->input->post('enabled');
			
			//save the message
			$page_id	= $this->option->save($save);
			
			$this->session->set_flashdata('message', 'Lưu dữ liệu thành công');
			
			//go back to the message list
			redirect('admin/options');
		}
	}
	
	function delete($id){
		$option	= $this->option->get_option($id);
		if($option){
			$this->option->delete_option($id);
			$this->session->set_flashdata('message', 'Xóa thành công');
		}else{
			$this->session->set_flashdata('error', 'Có lỗi xảy ra');
		}
		redirect('admin/options');
	}
}